<template>
  <el-dialog
    v-model="visible"
    :title="status ? $t('admin.resetPwd') : $t('admin.createAcc')"
    :close-on-click-modal="false"
    :width="lang === 'en'? '650px':'600px'"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      style="width:500px;"

      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('station.stationNames')"
        prop="stationName"
        style="width:500px;"
      >
        <el-input
          v-model="dataForm.stationName"
          disabled
        />
      </el-form-item>
      <el-form-item
        :label="$t('homes.userName')"
        prop="account"
        style="width:580px;"
      >
        <el-row style="width:100%">
          <el-col :span="20">
            <el-input
              v-model="dataForm.account"
              maxlength="50"
              show-word-limit
              class="account"
              :disabled="!editAccount"
              @change="checkAccount()"
            />
          </el-col>
          <el-col :span="4">
            <el-button
              v-if="!editAccount"
              type="text"
              @click="changeAccountInfo()"
            >
              <el-icon><EditPen /></el-icon>
              {{ $t("admin.modifyAcc") }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        :label="$t('sys.password')"
        prop="password"
        style="width:500px;"
        class="dataform-password"
      >
        <el-input
          v-model="dataForm.password"
          v-input-rule
          type="password"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.confirmPassword')"
        prop="passwordConfirm"
        style="width:500px;"
      >
        <el-input
          v-model="dataForm.passwordConfirm"
          v-input-rule
          type="password"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { encrypt } from '@/utils/crypto.js'
import { validPassword } from '@/utils/validate'

const emit = defineEmits(['refreshDataList'])
const lang = reactive(window.localStorage.getItem('bbcLang'))

const validateAccount = (rule, value, callback) => {
  const reg = /[^\w]/
  if (reg.test(value)) {
    callback(new Error(lang === 'en' ? 'The account can contain only digits or letters' : '账号只能为数字或字母'))
  } else if (!value.trim()) {
    callback(new Error($t('home.accNoNull')))
  }
  http({
    url: http.adornUrl('/admin/station/checkStationAccount'),
    method: 'GET',
    params: {
      stationId: dataForm.value.stationId,
      account: value
    }
  }).then(({ data }) => {
    if (!data) {
      callback(new Error($t('admin.accIsExist')))
    } else {
      callback()
    }
  })
}
// eslint-disable-next-line no-unused-vars
const validatePassword = (rule, value, callback) => {
  if (dataForm.value.password !== dataForm.value.passwordConfirm) {
    callback(new Error($t('admin.twoPwdIncon')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validatePwd = (rule, value, callback) => {
  if (validPassword(value)) {
    callback()
  } else {
    callback(new Error($t('passwordVerification')))
  }
}
const dataRule = {
  account: [
    { required: true, message: $t('admin.stationAccNoNull'), trigger: 'blur' },
    { validator: validateAccount, trigger: 'blur' }
  ],
  password: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validatePwd, trigger: 'blur' }
  ],
  passwordConfirm: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

const dataForm = ref({
  account: '',
  password: '',
  passwordConfirm: ''
})
const visible = ref(false)
const dataFormRef = ref(null)
const init = (stationId) => {
  dataForm.value.stationId = stationId || 0
  visible.value = true
  dataRule.password[0].required = true
  dataRule.passwordConfirm[0].required = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    dataForm.value.account = null
    dataForm.value.password = null
    dataForm.value.passwordConfirm = null
    getDataInfo()
  })
}
defineExpose({ init })

const editAccount = ref(true)
const status = ref(true)
/**
 * 获取店铺详情数据
 */
const getDataInfo = () => {
  http({
    url: http.adornUrl('/admin/station/info/' + dataForm.value.stationId),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
    dataForm.value.password = ''
    status.value = !!data.account
    editAccount.value = !dataForm.value.account
  })
}

const changeAccountInfo = () => {
  editAccount.value = true
}
const checkAccount = () => {
  dataForm.value.account = dataForm.value.account.trim()
}

/**
 * 表单提交
 */
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      const data = JSON.parse(JSON.stringify(dataForm.value))
      data.password = encrypt(data.password)
      data.passwordConfirm = encrypt(data.passwordConfirm)
      http({
        url: http.adornUrl('/admin/station/changeAccountInfo'),
        method: 'put',
        data: http.adornData(data)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}
</script>

<style scoped>
.account :deep(.el-input__inner) {
  padding-right: 45px !important;
}
.dataform-password  :deep(.el-form-item__error){
  white-space: nowrap;
}
</style>
